<?php


namespace App\GatewayWorker;

use GatewayWorker\Lib\Gateway;
use Illuminate\Support\Facades\Log;

class Event
{
    const ERROR_CHAT = 1001;  // 聊天室异常

    const SOCKET_RESPONSE_TYPE_SYSTEM = 'system';
    const SOCKET_RESPONSE_TYPE_USER = 'user';
    const SOCKET_RESPONSE_TYPE_INIT = 'init';

    const SOCKET_MSG_TYPE_USER = 'text';

    // 单worker启动时候
    public static function onWorkerStart($businessWorker)
    {
        // 记录聊天信息id
        global $message_id;
        $message_id = 0;
    }

    // 当有用户连接时
    public static function onConnect($client_id)
    {
        global $connection_count;  // 统计连接数量
        ++ $connection_count;
    }

    // 当onWebSocketConnect连接时候
    public static function onWebSocketConnect($client_id, $data)
    {
        // todo 连接WebSocket
    }

    // 监听客户端信息
    public static function onMessage($client_id, $data)
    {
        global $message_id;
        ++ $message_id;

        // 标准返回客户端结构
        $response = [
            "type" => self::SOCKET_RESPONSE_TYPE_SYSTEM,
            "msg" => [
                "id" => $message_id,  // 聊天信息id
                "type" => self::SOCKET_MSG_TYPE_USER,
                "content" => [  // 返回内容
                    "text" => "",
                ],
            ],
            'errcode' => 0,
        ];

        $data = json_decode($data);

        if (!isset($data->type)) {
            $response['msg'] = 'insufficient parameters';
            $response['errcode'] = self::ERROR_CHAT;
            Gateway::sendToClient($client_id, json_encode($response));
            return false;
        }

        switch ($data->type) {
            case 'init':
                // todo 判断该uid是否已经绑定
                // 绑定用户
                Gateway::bindUid($client_id, $data->uid);
                $response['msg']['content']['text'] = '进入直播间';
                $response['msg']['type'] = self::SOCKET_RESPONSE_TYPE_INIT;
                // 发送给当前uid客户端
                Gateway::sendToUid($data->uid, json_encode($response));
                break;
            case 'user':
                // 判断用户是否在线
                if (Gateway::isUidOnline($data->msg->userinfo->uid) == 0) {  // 0表示不在线, 1表示在线
                    $response['msg'] = 'insufficient authority';
                    $response['errcode'] = self::ERROR_CHAT;
                    // todo 返回异常消息或者记录异常消息, 也可以不返回给客户端
                } else {
                    $data->msg->id = $message_id;
                    // 把消息推送到直播间
                    Gateway::sendToAll(json_encode($data));
                }
                break;
            default :
                $response['msg'] = 'insufficient authority';
                $response['errcode'] = self::ERROR_CHAT;
                // todo 返回异常消息或者记录异常消息, 也可以不返回给客户端
                break;
        }
    }

    public static function onClose($client_id)
    {
        global $connection_count;
        $connection_count --;
        // 关闭连接
        Log::info('close connection' . $client_id);
    }

}